<?php
namespace app\middleware;

use app\service\JwtService;
use plugin\saiadmin\exception\ApiException;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class JwtMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 排除不需要验证的路由
        $excludeRoutes = [
            '/api/login',
            '/api/upload/image',
            '/api/upload/file',
            '/api/system/index',
            '/api/system/banner',
            '/api/console/levelEndtime',
            
        ];

        if (in_array($request->path(), $excludeRoutes)) {
            return $handler($request);
        }

        try {
            // 获取token
            $token = JwtService::getRequestToken();
            if (empty($token)) {
                throw new ApiException('请先登录', 401);
            }

            // 验证token
            $userData = JwtService::validateToken($token);
            
            // 将用户信息添加到请求中
            $request->userData = $userData;
            
            return $handler($request);
        } catch (ApiException $e) {
            return json([
                'code' => $e->getCode() ?: 401,
                'msg' => $e->getMessage(),
                'data' => null
            ]);
        }
    }
}
